function M = slassignmap(a, n, op)
%SLASSIGNMAP Constructs a logical matrix representing assignment
%
% [ Syntax ]
%   - M = slassignmap(a, n)
%   - M = slassignmap(a, labels)
%   - M = slassignmap(a, n, 'sparse')
%
% [ Arguments ]
%   - a:        the vector giving the assignment of each element
%   - n:        the number of targets that can be assigned to
%   - M:        the constructed logical map
%
% [ Description ]
%   - M = slassignmap(a, n) constructs a logical matrix as follows. 
%
%       - If a is an 1 x m row vector, then M is an n x m matrix, with
%         M(i, j) = 1 when a(j) = i, and M(i, j) = 0 otherwise.
%       - If a is an m x 1 column vector, then M is an m x n matrix, with
%         M(i, j) = 1 when a(i) = j, and M(i, j) = 0 otherwise.
%     
%     By default, M is a full matrix. If n is omitted, it is set to max(a).
%
%   - M = slassignmap(a, n, 'sparse') creates M as a sparse matrix.
%     
% [ History ]
%   - Created by Dahua Lin, on Dec 19, 2007
%

%% parse and verify input arguments

assert(isvector(a) && isnumeric(a), 'sltoolbox:slassignmap:invalidarg', ...
    'a should be a numeric vector.');

assert(isscalar(n) && n >= max(a), 'sltoolbox:slassignmap:invalidarg', ...
    'n should be a numeric scalar >= max(a)');

if nargin >= 3
    assert(ischar(op) && strcmp(op, 'sparse'), ...
        'sltoolbox:slassignmap:invalidarg', ...
        'The 3rd argument is invalid.');
    
    make_sparse = true;
else
    make_sparse = false;
end
   

%% main

% prepare subscripts

m = length(a);
if size(a, 1) == 1  % is row vector    
    i = a;
    j = 1 : m;    
    s = true(1, m);
    nr = n;
    nc = m;
else                % is column vector
    i = (1 : m)';
    j = a;
    s = true(m, 1);
    nr = m;
    nc = n;
end

% make matrix

if make_sparse
    M = sparse(i, j, s, nr, nc);     
else
    M = false(nr, nc);
    M(sub2ind(size(M), i, j)) = true;
end


